#!/bin/bash

## This script searches for all dbunit dataset .yml files, then
## it searches all integration tests for a reference to that .yml file.
## If none found, the .yml file is reported and an error status code is returned.


set -u

red="\e[91m"
normal="\e[0m"
bold="\e[1m"

status=0

dbunit_project="http-server"

## Loop over all .yml dataset files
while read -r dataSetFilePath; do
  
  ## Determine the .yml file reference we should look for. To do this, remove
  ## the dataset path prefix, eg:
  ## integration-testing/src/test/resources/datasets/very/test.yml -> very/test.yml
  dataSetFile=${dataSetFilePath/${dbunit_project}\/src\/test\/resources\/datasets\//}
  
  ## Next, loop over all tests and set 'found=1' if we find a reference to the target dataSetFile
  found=0
  while read -r testFile; do
    if grep -q "$dataSetFile" "$testFile"; then
      found=1
      break
    fi 
  done <<< "$(find "${dbunit_project}/src/test/java" -type f -name "*java")"

  ## If 'found==0', we did not find the dataSetFile, report it and flag and error status code
  if [ "$found" -eq 0 ]; then
   echo -e "${red}$dataSetFilePath${normal}"
   status=1
  fi
done <<< "$(find "${dbunit_project}/src/test/resources/datasets" -type f -name "*yml")"


if [ "$status" -eq 1 ]; then
  echo -e "${bold}Found unused db-unit test data files. Delete these files or use them in a dbunit test.${normal}"
fi

exit "$status"

